package com.ruoyi.web.controller.system;

import java.util.*;
import java.util.stream.Collectors;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.CodeGenerateUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.SysApplication;
import com.ruoyi.system.domain.SysTenantApplication;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysTenantApplicationService;
import org.apache.ibatis.javassist.compiler.CodeGen;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.SysTenant;
import com.ruoyi.system.service.ISysTenantService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 租户信息Controller
 * 
 * @author kuaidou
 * @date 2021-08-20
 */
@Controller
@RequestMapping("/system/tenant")
public class SysTenantController extends BaseController
{
    private String prefix = "system/tenant";

    @Autowired
    private ISysTenantService sysTenantService;

    @Autowired
    private ISysTenantApplicationService sysTenantApplicationService;

    @Autowired
    private ISysConfigService sysConfigService;


    @RequiresPermissions("system:tenant:view")
    @GetMapping()
    public String tenant()
    {
        return prefix + "/tenant";
    }

    /**
     * 查询租户信息列表
     */
    @RequiresPermissions("system:tenant:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(SysTenant sysTenant)
    {
        startPage();
        List<SysTenant> list = sysTenantService.selectSysTenantList(sysTenant);
        return getDataTable(list);
    }

    /**
     * 导出租户信息列表
     */
    @RequiresPermissions("system:tenant:export")
    @Log(title = "租户信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(SysTenant sysTenant)
    {
        List<SysTenant> list = sysTenantService.selectSysTenantList(sysTenant);
        ExcelUtil<SysTenant> util = new ExcelUtil<SysTenant>(SysTenant.class);
        return util.exportExcel(list, "租户信息数据");
    }

    /**
     * 新增租户信息
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存租户信息
     */
    @RequiresPermissions("system:tenant:add")
    @Log(title = "租户信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(SysTenant sysTenant)
    {
        sysTenant.setTenantCode(CodeGenerateUtils.tenantCodeGenerate());
        return toAjax(sysTenantService.insertSysTenant(sysTenant));
    }

    /**
     * 修改租户信息
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        SysTenant sysTenant = sysTenantService.selectSysTenantById(id);
        mmap.put("sysTenant", sysTenant);
        return prefix + "/edit";
    }

    /**
     * 修改保存租户信息
     */
    @RequiresPermissions("system:tenant:edit")
    @Log(title = "租户信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(SysTenant sysTenant)
    {
        return toAjax(sysTenantService.updateSysTenant(sysTenant));
    }

    /**
     * 删除租户信息
     */
    @RequiresPermissions("system:tenant:remove")
    @Log(title = "租户信息", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(sysTenantService.deleteSysTenantByIds(ids));
    }

    /**
     * 分配子系统
     *
     * @param tenantCode
     * @param mmap
     * @return
     */
    @GetMapping("/authApplication/{tenantCode}")
    public String authApplication(@PathVariable("tenantCode") String tenantCode, ModelMap mmap) {
        SysTenant sysTenant = sysTenantService.selectTenantByTenantCode(tenantCode);
        mmap.put("tenant", sysTenant);
        // 获取所有可分配给租户的子系统
        SysApplication application = new SysApplication();
        application.setAppType(sysTenant.getType());
        List<SysApplication> applications = sysTenantService.selectSysApplicationAuthList(application);
        if (!CollectionUtils.isEmpty(applications)) {
            // 判断哪些是选中状态
            List<SysTenantApplication> sysTenantApplications = sysTenantApplicationService.selectSysTenantApplicationByTenantCode(tenantCode);
            for (SysTenantApplication tenantApplication : sysTenantApplications) {
                for (SysApplication sysApplication : applications) {
                    if (sysApplication.getAppCode().equals(tenantApplication.getAppCode())) {
                        sysApplication.setFlag(true);
                    }
                }
            }
        }
        mmap.put("applications", applications);
        return prefix + "/authApplication";
    }

    /**
     * 保存租户子系统
     */
    @RequiresPermissions("system:tenant:auth")
    @Log(title = "租户分配子系统", businessType = BusinessType.UPDATE)
    @PostMapping("/authApplication")
    @ResponseBody
    public AjaxResult authApplication(@RequestBody SysTenantApplication sysTenantApplication) {
        SysApplication application = new SysApplication();
        application.setAppType(sysTenantApplication.getType());
        List<SysApplication> applications = sysTenantService.selectSysApplicationAuthList(application);
        Map<String, Date> appCodeMaps = new TreeMap<>();
        Map<String, Integer> appCodeFreeDateMaps = applications.stream().filter(sysApplication -> sysTenantApplication.getAppCodes().contains(sysApplication.getAppCode()))
                .collect(Collectors.toMap(SysApplication::getAppCode, SysApplication::getFreeDate));
        appCodeFreeDateMaps.keySet().forEach(appCode -> {
            Integer freeDate = appCodeFreeDateMaps.get(appCode);
            if (freeDate != null && freeDate > 0) {
                appCodeMaps.put(appCode, DateUtils.addDays(DateUtils.getNowDate(), freeDate));
            } else {
                appCodeMaps.put(appCode, DateUtils.addDays(DateUtils.getNowDate(), Constants.DAYS));
            }
        });
        sysTenantApplication.setAppCodeMaps(appCodeMaps);
        sysTenantService.authApplication(sysTenantApplication,
                sysTenantService.selectTenantByTenantCode(sysTenantApplication.getTenantCode()));
        return success();
    }

}